package com.lanqiao.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;

public class MyJson {
    public static String toJsonString(Object object){
        Class clazz = object.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        StringBuffer stringBuffer = new StringBuffer("{");
        //遍历所有方法
        for (int i=0;i<methods.length;i++){
            Method method = methods[i];
            //获取GET方法
            if (method.getName().substring(0,3).equals("get")){
                //getName   首字母大小写转换
                stringBuffer.append("\""+method.getName().substring(3,4).toLowerCase()+ method.getName().substring(4)+"\"");
                stringBuffer.append(":");
                //调用get方法取值
                Object result =null;
                try {
                    result=method.invoke(object,null);  //调用方法  第一个参数是实例对象，第二个参数是参数列表
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (result instanceof String){
                    stringBuffer.append("\"" + String.valueOf(result)+"\"");
                }else {
                    stringBuffer.append(String.valueOf(result));
                }
//                if (i!=methods.length-1){
//                    stringBuffer.append(",");
//                }
                stringBuffer.append(",");
            }
        }
        stringBuffer.delete(stringBuffer.length()-1,stringBuffer.length());
        stringBuffer.append("}");
        return stringBuffer.toString();
    }

}
